# -*- coding:utf-8 -*-

import sys, socket, json, threading

from PyQt5.QtWidgets import (QApplication, QWidget, QDesktopWidget, QMessageBox, 
                            QPushButton, QTextEdit, QLineEdit, QToolTip, QLabel,
                            QTextEdit, QMessageBox, QProgressDialog, QComboBox,
                            QHBoxLayout, QFrame, QSplitter, QStyleFactory)
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtCore import QCoreApplication, Qt

HOST = "127.0.0.1" # 服务器ip
PORT = 80 # 服务器端口号
ADDR = (HOST, PORT) # 服务器地址

class Login(QWidget):
    def __init__(self):
        # 初始界面
        super().__init__()
        self.initUI()

    def initUI(self):
        # 界面大小，标题， 图标
        self.setGeometry(500, 500, 300, 300)
        self.center()
        self.setWindowTitle("三人俄罗斯方块")
        self.setWindowIcon(QIcon("眼镜蛇.png"))

        # 创建label
        self.lab1 = QLabel("用户名", self)
        self.lab1.setGeometry(20, 50, 100, 30)
        self.lab2 = QLabel("服务器地址", self)
        self.lab2.setGeometry(20, 100, 100, 30)

        # 创建用输入框
        self.current_username = QLineEdit("请输入用户名", self)
        self.current_username.setGeometry(100, 50, 150, 30)
        self.current_username.selectAll()
        self.addr_input = QLineEdit("", self)
        self.addr_input.setGeometry(100, 100, 150, 30)
        
        # 设置提示文本字体和大小
        QToolTip.setFont(QFont("SansSerif", 10))
        # 设置文本提示
        self.addr_input.setToolTip("公网连接无需填写，局域网内填写地址")

        # 获得主机名
        self.hostname = socket.gethostname()

        # 用户名
        if len(self.hostname) != 0:
            self.current_username.setText(self.hostname)
            self.current_username.selectAll()

        # 设置聚焦
        self.current_username.setFocus()

        # 退出键
        self.quit_btn = QPushButton("退出", self)
        self.quit_btn.clicked.connect(QCoreApplication.instance().quit)
        self.quit_btn.resize(100, 30)
        self.quit_btn.move(170, 200)

        # 登录键
        self.login_btn = QPushButton("登录", self)
        self.login_btn.resize(100, 30)
        self.login_btn.move(30, 200)
        self.login_btn.clicked.connect(self.login)
        self.show()

    def login(self):
        # 登录提示
        current_name = self.current_username.text()
        if len(self.addr_input.text()) != 0:
            conn_info = self.addr_input.text()
            HOST = self.addr_input.text().split(":")[0]
            PORT = int(self.addr_input.text().split(":")[1])
        else:
            pass
        if len(current_name) == 0:
            current_name = "用户名为空"
            QMessageBox.about(self, "警报", current_name)
            self.username.clear()
            self.username.setFocus()
        else:
            QMessageBox.about(self, "用户名", "用户名:" + current_name)
            self.client = socket.socket()
            self.client.connect(ADDR)
            self.menu = Menu()
            self.menu.getconnect(current_name, self.client)
            self.menu.show()
            self.hide()

    def showprogress(self):
        # 进度条
        self.progress = QProgressDialog(self)
        self.progress.setWindowTitle("登录")
        self.progress.setLabelText("正在连接中")
        self.progress.setCancelButtonText("取消")
        self.progress.setMinimumDuration(5)
        self.progress.setWindowModality(Qt.WindowModal)
        self.progress.setRange(0, 100000)
        for i in range(100000):
            self.progress.setValue(i)
            if self.progress.wasCanceled():
                QMessageBox.warning(self, "提示", "操作失败")
                break
        else:
            self.progress.setValue(100000)

    def center(self):
        # 界面居中
        self.qr = self.frameGeometry()
        self.cp = QDesktopWidget().availableGeometry().center()
        self.qr.moveCenter(self.cp)
        self.move(self.qr.topLeft())

    def closeEvent(self, event):
        # 关闭提示
        reply = QMessageBox.question(self, '三人贪吃蛇',"你确定要离开吗？",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

# 主菜单，消息列表 
class Menu(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # menu页
        self.setGeometry(300, 300, 300, 300)
        self.center()
        self.setWindowTitle("三人俄罗斯方块")
        self.setWindowIcon(QIcon("眼镜蛇.png"))

        self.title = QLabel("    系统消息", self)
        self.title.setGeometry(0, 0, 300, 20)

        self.user_lab1 = QLabel("房主:", self)
        self.user_lab1.setGeometry(20, 180, 50, 20)
        
        self.user_lab2 = QLabel("玩家一:", self)
        self.user_lab2.setGeometry(120, 180, 50, 20)

        self.user_lab3 = QLabel("玩家二:", self)
        self.user_lab3.setGeometry(210, 180, 50, 20)

        self.username_lab1 = QLabel("", self)
        self.username_lab1.setGeometry(50, 180, 50, 20)

        self.username_lab2 = QLabel("", self)
        self.username_lab2.setGeometry(160, 180, 50, 20)

        self.username_lab3 = QLabel("", self)
        self.username_lab3.setGeometry(250, 180, 50, 20)

        # 消息列表
        self.msg_list = QTextEdit("",self)
        self.msg_list.setGeometry(10, 20, 280, 150)

        self.lab1 = QLabel("难度", self)
        self.lab1.setGeometry(10, 220, 30, 20)

        self.lab2 = QLabel("速度", self)
        self.lab2.setGeometry(10, 250, 30, 20)

        self.lab3 = QLabel("", self)
        self.lab3.setGeometry(150 , 250, 30, 30)

        self.double_box1 = QComboBox(self)
        self.double_box1.setGeometry(50, 220, 60, 20)
        self.double_box1.addItem("1")
        self.double_box1.addItem("2")
        self.double_box1.addItem("3")
        self.double_box1.addItem("4")

        self.double_box2 = QComboBox(self)
        self.double_box2.setGeometry(50, 250, 60, 20)
        self.double_box2.addItem("1")
        self.double_box2.addItem("2")
        self.double_box2.addItem("3")
        self.double_box2.addItem("4")

        self.double_box1.currentTextChanged.connect(self.get_difficulty)
        self.double_box2.currentTextChanged.connect(self.get_speed)

        self.start_btn = QPushButton("", self)
        self.start_btn.setIcon(QIcon("播放1.png"))
        self.start_btn.setGeometry(200, 220, 50, 50)

        # 设置文本框只可读
        self.msg_list.setReadOnly(True)
    
    def get_difficulty(self):
        # 监听并获取难度等级
        self.difficulty = self.double_box1.currentText()
        print("难度等级" + self.difficulty)
    
    def get_speed(self):
        # 监听并获取方块下降速度
        self.speed = self.double_box2.currentText()
        print("下降速度" + self.speed)


    def getconnect(self, username, client):
        # 传递用户名与连接
        self.username = username
        self.client = client
        self.data = {}
        self.data["username"] = username
        self.data["behavior"] = "enter"
        self.client.send((json.dumps(self.data)).encode("utf-8"))
        self.msg = json.loads((self.client.recv(40960)).decode("utf-8"))
        print(self.msg)
        if self.msg["result"] == "OK":
            self.showprogress()
            self.msg_list.append("服务器连接成功")
            self.msg_list.append("server: " + self.msg["reason"])
            if self.msg["number"] == 0:
                self.msg_list.append("system: " + username + " 成为房主")
                self.username_lab1.setText(username)
                if self.msg["room_content"] == 0:
                    pass
                elif self.msg["room_content"] == 1:
                    pass
                elif self.msg["room_content"] == 2:
                    self.username_lab2.setText(self.msg["new_user2"])
                    self.msg_list.append("system: " + self.msg["new_user2"] + "成为玩家2")
                elif self.msg["room_content"] == 3:
                    self.username_lab2.setText(self.msg["new_user2"])
                    self.msg_list.append("system: " + self.msg["new_user2"] + "成为玩家2")
                    self.username_lab3.setText(self.msg["new_user3"])
                    self.msg_list.append("system: " + self.msg["new_user3"] + "成为玩家3")
            else:
                self.msg_list.append("system: " + username + " 成为玩家" + 
                                    str(self.msg["number"] + 1))
                # if (self.msg["number"] + 1) == 2:
                #     self.username_lab2.setText(username)
                # elif (self.msg["number"] + 1) == 3:
                #     self.username_lab3.setText(username)
                if self.msg["room_content"] == 0:
                    pass
                elif self.msg["room_content"] == 1:
                    pass
                elif self.msg["room_content"] == 2:
                    self.username_lab1.setText(self.msg["new_roomer"])
                    self.msg_list.append("system: " + self.msg["new_roomer"] + " 是房主")
                    self.username_lab2.setText(self.msg["new_user2"])
                    self.username_lab3.setText("")
                elif self.msg["room_content"] == 3:
                    self.username_lab1.setText(self.msg["new_roomer"])
                    self.msg_list.append("system: " + self.msg["new_roomer"] + " 是房主")
                    self.username_lab2.setText(self.msg["new_user2"])
                    self.msg_list.append("system: " + self.msg["new_user2"] + " 是玩家2")
                    self.username_lab3.setText(self.msg["new_user3"])
                
        elif self.msg["result"] == "refuse":
            self.showprogress()
            self.msg_list.append("服务器连接失败")
            self.msg_list.append("error: " + self.msg["reason"])
        
        chat = threading.Thread(target=self.manage, args=())
        chat.start()

    def manage(self):
        # 消息监听
        while True:
            self.rec = self.client.recv(40960)
            print(self.rec)
            self.rec = json.loads((self.rec).decode("utf-8"))
            print(self.rec)
            if self.rec["result"] == "OK":
                if self.rec["behavior"] == "add new user":
                    self.msg_list.append("system: " + "玩家" + 
                                        str(self.rec["new_user_number"] + 1) + 
                                        " " + str(self.rec["new_username"]) + " 加入房间")
                    if self.rec["room_content"] == 0:
                        self.username_lab1.setText("")
                        self.username_lab2.setText("")
                        self.username_lab3.setText("")
                    elif self.rec["room_content"] == 1:
                        self.username_lab1.setText(self.rec["new_roomer"])
                        self.username_lab2.setText("")
                        self.username_lab3.setText("")
                    elif self.rec["room_content"] == 2:
                        self.username_lab1.setText(self.rec["new_roomer"])
                        self.username_lab2.setText(self.rec["new_user2"])
                        self.username_lab3.setText("")
                    elif self.rec["room_content"] == 3:
                        self.username_lab1.setText(self.rec["new_roomer"])
                        self.username_lab2.setText(self.rec["new_user2"])
                        self.username_lab3.setText(self.rec["new_user3"])
                        
                elif self.rec["behavior"] == "user leave":
                    if self.rec["leave_username"] == self.username:
                        self.msg_list.append("system: 本机离开房间")
                    else:
                        self.msg_list.append("system: 玩家"+ 
                                            str(self.rec["leave_user_number"] + 1)+ 
                                            " " + str(self.rec["leave_username"]) + 
                                            " 离开房间")
                        print(self.rec["leave_user_number"])
                        if (self.rec["room_content"]) == 0:
                            self.username_lab1.setText("")
                            self.username_lab2.setText("")
                            self.username_lab3.setText("")
                        elif (self.rec["room_content"]) == 1:
                            self.username_lab1.setText(self.rec["new_roomer"])
                            self.username_lab2.setText("")
                            self.username_lab3.setText("")
                            self.msg_list.setText("system: 房间中剩余玩家为 房主 " + self.rec["new_roomer"] + " 其余玩家已离开")
                        elif (self.rec["room_content"]) == 2:
                            self.username_lab1.setText(self.rec["new_roomer"])
                            self.username_lab2.setText(self.rec["new_user2"])
                            self.username_lab3.setText("")
                        elif (self.rec["room_content"]) == 3:
                            self.username_lab1.setText(self.rec["new_roomer"])
                            self.username_lab2.setText(self.rec["new_user2"])
                            self.username_lab3.setText(self.rec["new_user3"])
                elif self.rec["behavior"] == "roomer leave":
                    self.msg_list.append("system: 房主 " + self.rec["leave_username"] + " 离开房间")
                    if (self.rec["room_content"]) == 0:
                        self.username_lab1.setText("")
                        self.username_lab2.setText("")
                        self.username_lab3.setText("")
                    elif (self.rec["room_content"]) == 1:
                        self.username_lab1.setText(self.rec["new_roomer"])
                        self.username_lab2.setText("")
                        self.username_lab3.setText("")
                        self.msg_list.append("system: " + self.rec["new_roomer"] + " 成为房主")
                    elif (self.rec["room_content"]) == 2:
                        self.username_lab1.setText(self.rec["new_roomer"])
                        self.username_lab2.setText(self.rec["new_user2"])
                        self.username_lab3.setText("")
                        self.msg_list.append("system: " + self.rec["new_roomer"] + " 成为房主")
                        self.msg_list.append("system: " + self.rec["new_user2"] + " 成为玩家2")
                    elif (self.rec["room_content"]) == 3:
                        self.username_lab1.setText(self.rec["new_roomer"])
                        self.username_lab2.setText(self.rec["new_user2"])
                        self.username_lab3.setText(self.rec["new_user3"])
                        self.msg_list.append("system: " + self.rec["new_roomer"] + " 成为房主")
                        self.msg_list.append("system: " + self.rec["new_user2"] + " 成为玩家2")
                        self.msg_list.append("system: " + self.rec["new_user3"] + " 成为玩家3")

    def showprogress(self):
        # 进度条
        self.progress = QProgressDialog(self)
        self.progress.setWindowTitle("登录")
        self.progress.setLabelText("正在连接中")
        self.progress.setCancelButtonText("取消")
        self.progress.setMinimumDuration(5)
        self.progress.setWindowModality(Qt.WindowModal)
        self.progress.setRange(0, 50000)
        for i in range(50000):
            self.progress.setValue(i)
            if self.progress.wasCanceled():
                QMessageBox.warning(self, "提示", "操作失败")
                break
        else:
            self.progress.setValue(50000)

    def center(self):
        # 界面居中
        self.qr = self.frameGeometry()
        self.cp = QDesktopWidget().availableGeometry().center()
        self.qr.moveCenter(self.cp)
        self.move(self.qr.topLeft())

    def closeEvent(self, event):
        # 关闭提示
        reply = QMessageBox.question(self, '三人贪吃蛇',"你确定要离开吗？",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.data["behavior"] = "quit"
            self.client.sendall((json.dumps(self.data)).encode("utf-8"))
            event.accept()
        else:
            event.ignore()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    login = Login()
    sys.exit(app.exec_())